package com.example.simple_android;

import com.example.simple_android.Manager.impl.BroadcastReceiverManager;
import com.example.simple_android.annotation.InjectionMark;
import com.example.simple_android.annotation.ScannerPackage;
import com.example.simple_android.annotation.impl.InjectionImpl;
import com.example.simple_android.annotation.impl.InjectionMarkImpl;
import com.example.simple_android.annotation.impl.ReceiverImpl;
import com.example.simple_android.utils.ReflectionsUtil;

import java.util.Objects;

@InjectionMark(staticMethod = "getInstance")
@ScannerPackage(packageName = "com.example.simple_android")
public class Application extends android.app.Application {

    /**
     * 此变量中，保存着程序运行时的全局唯一变量
     */
    private static Application application;

    public Application() {
        super();
        application = this;
    }

    /**
     * 调用此方法，获取程序运行时，此类的唯一对象
     *
     * @return 此类在全局中的唯一变量
     */
    public static Application getInstance() {
        return application;
    }

    /**
     * 程序运行时，将用于程序初始化的一些动作
     */
    @Override
    public void onCreate() {
        super.onCreate();
        Class<? extends Application> aClass = this.getClass();
        ScannerPackage declaredAnnotation = aClass.getDeclaredAnnotation(ScannerPackage.class);
        String packageName = Objects.requireNonNull(declaredAnnotation).packageName();
        ReflectionsUtil.init(this, packageName);
        // 自动初始化被InjectionMark标记的类
        InjectionMarkImpl.injectionMarkClass();
        // 自动注入被Injection标记的Field
        InjectionImpl.injection();
        // 注册广播接收者
        ReceiverImpl.initReceiver(this);
    }

    /**
     * 当程序结束时，用于做一些程序关闭时的必要操作
     */
    @Override
    public void onTerminate() {
        super.onTerminate();
        // 注销广播接收者
        BroadcastReceiverManager.getInstance().clear();
    }
}
